package pkg

import (
	"bytes"
	"context"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"homepage_srv/homepage"
	"log"
	"smart-health-platforms/config"
)

type ES struct {
	Id    string
	Index string
	Body  interface{}
}

// 同步es
func (e *ES) SyncEs() error {
	// Build the request body.
	data, err := json.Marshal(e.Body)
	if err != nil {
		log.Fatalf("Error marshaling document: %s", err)
	}

	// Set up the request object.
	req := esapi.IndexRequest{
		Index:      e.Index,
		DocumentID: e.Id,
		Body:       bytes.NewReader(data),
		Refresh:    "true",
	}

	// Perform the request with the client.
	res, err := req.Do(context.Background(), config.Es)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
	return nil
}

// 搜索
func Search(keyword string) (item []*homepage.GoodSearch) {
	var (
		r map[string]interface{}
	)
	// 3. Search for the indexed documents
	//
	// Build the request body.
	var buf bytes.Buffer
	query := map[string]interface{}{}
	if keyword != "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"Name": keyword,
				},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	}
	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}
	// Perform the search request.
	res, err := config.Es.Search(
		config.Es.Search.WithContext(context.Background()),
		config.Es.Search.WithIndex("search_test"),
		config.Es.Search.WithBody(&buf),
		config.Es.Search.WithTrackTotalHits(true),
		config.Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	if err = json.NewDecoder(res.Body).Decode(&r); err != nil {
		log.Fatalf("Error parsing the response body: %s", err)
	}
	// Print the ID and document source for each hit.
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		source := hit.(map[string]interface{})["_source"].(map[string]interface{})
		item = append(item, &homepage.GoodSearch{
			Id:               int64(source["ID"].(float64)),
			BrandName:        source["Name"].(string),
			BrandDescription: source["Desc"].(string),
			MainImage:        source["SerialNumber"].(string),
			StoreName:        source["Name"].(string),
			Sales:            uint64(source["Status"].(float64)),
			StoreInfo:        source["Desc"].(string),
		})
	}
	return
}
